package com.itheima.service.Impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dto.LoginDto;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import com.itheima.vo.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
   /* @Override
    public PageBean<Emp> finByPage(Integer page, Integer pageSize) {

        // 开启分页
        PageHelper.startPage(page,pageSize);

        //执行查询
        Page<Emp> p=(Page<Emp>)empMapper.findList2();

        return  new PageBean<Emp>(p.getTotal(),p.getResult());
    }*/
    @Override
    public PageBean<Emp> finByPage(Integer page, Integer pageSize, String name, Integer gender, LocalDate begin, LocalDate end) {

        // 开启分页
        PageHelper.startPage(page,pageSize);

        //执行查询
        Page<Emp> p=(Page<Emp>)empMapper.findList3(name,gender,begin,end);

        return  new PageBean<Emp>(p.getTotal(),p.getResult());
    }

    @Override
    public void save(Emp emp) {
        //md5 加密技术
        emp.setPassword(SecureUtil.md5("123456"));
        emp.setCreateTime(LocalDate.now());
        emp.setUpdateTime(LocalDate.now());
        empMapper.save(emp);
    }

    @Override
    public Emp selectById(Integer id) {
       return empMapper.selectById(id);

    }

    @Override
    public void update(Emp emp) {
        emp.setUpdateTime(LocalDate.now());
        empMapper.update(emp);
    }

    @Override
    public void delete(List<Integer> ids) {
        empMapper.delete(ids);
    }

    @Override
    public Integer selectByDeptId(Integer id) {
      return   empMapper.selectByDeptId(id);

    }

    @Override
    public Emp login(LoginDto loginDto) {
        //StrUtil.isEmpty()  糊涂工具的判断 是否为空
        if (StrUtil.isEmpty(loginDto.getUsername())||StrUtil.isEmpty(loginDto.getPassword())){
            throw new BusinessException("用户名和密码不能为空");  //抛出自定义异常
        }
         Emp emp= empMapper.findByUserName(loginDto.getUsername());  //通过传入的用户名判断用户是否存在
        if (emp==null){
            throw new BusinessException("用户名不存在");
        }
        String pass=SecureUtil.md5(loginDto.getPassword());   //将传入的密码 进行md5加密
        if (!StrUtil.equals(pass,emp.getPassword())){       //将加密过后的密码和通过用户名查出来的密码 emp.getPassWorrd进行比较
            throw  new BusinessException("密码错误");
        }
        return emp;
    }
}
